package cn.wit.summit.chwan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.AdPosition;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.adapters.RecommendAdapter;
import cn.wit.summit.chwan.adapters.RecommendSkeletonAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.db.NetResultCacheTable;
import cn.wit.summit.chwan.models.dbmanager.NetResultCacheManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.ViewBean;
import cn.wit.summit.chwan.models.event.AccountChangeEvent;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.event.SensorChangedEvent;
import cn.wit.summit.chwan.models.response.IndexBeanResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.activity.SearchActivity;
import cn.wit.summit.chwan.ui.base.BaseAppCompatActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.CountdownView;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemBestMonthDownButn;
import cn.wit.summit.chwan.widgets.ItemGridDownloadBestView;
import cn.wit.summit.chwan.widgets.ItemGridDownloadView;
import cn.wit.summit.chwan.widgets.ItemListPartView;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadView;
import cn.wit.summit.chwan.widgets.RecommendTopEnergyView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import cn.wit.summit.chwan.widgets.skeleton.Skeleton;
import cn.wit.summit.chwan.widgets.skeleton.SkeletonScreen;
import retrofit2.Retrofit;

/**
 * 推荐
 * Created by Alan on 2018/4/11.
 */

public class RecommendFragment extends BaseFragment implements View.OnClickListener
        , CountdownView.OnCountdownListener {
    private String TAG = "RecommendFragment";

    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.headerLl)
    LinearLayout headerLl;
    @Bind(R.id.recommendTopAdIv)
    SimpleDraweeView recommendTopAdIv;
    @Bind(R.id.recommendTopEnergyTop)
    RecommendTopEnergyView recommendTopEnergyTop;
    @Bind(R.id.recommendTopDownloadTop)
    RecommendTopDownloadView recommendTopDownloadTop;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.tagNameTx)
    TextView tagNameTx;
    @Bind(R.id.recommendTopNameTx)
    TextView recommendTopNameTx;
    @Bind(R.id.tagNumTx)
    TextView tagNumTx;
    @Bind(R.id.recommendTopNumTx)
    TextView recommendTopNumTx;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.notNetFl)
    FrameLayout notNetFl;
    @Bind(R.id.part_search_tx)
    TextView partSearchTx;
    @Bind(R.id.recommendTopEnergy)
    RecommendTopEnergyView recommendTopEnergy;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadView recommendTopDownload;
    @Bind(R.id.back)
    ImageView back;

    private RecommendAdapter adapter;
    private List<RecommendAdapter.ViewBean> viewBeans = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private JumpBaseBean recommendTopAd = null;

    private int pn = 1;
    private int poDotCo = 2;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend_new, null);
        ButterKnife.bind(this, view);

        recommendTopEnergy.setVisibility(View.GONE);
        recommendTopDownload.setVisibility(View.GONE);
        back.setVisibility(View.GONE);
        notNetFl.setVisibility(View.GONE);

        barTitleTx.setText(getResources().getString(R.string.title_home));
        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        initView();
        EventBus.getDefault().register(this);
        initData();
        return view;
    }

    List<ViewBean> mDatasSkeleton = new ArrayList<>();
    private SkeletonScreen skeletonScreen;
    private void initSkeleton() {
        RecommendSkeletonAdapter skeletonAdapter = new RecommendSkeletonAdapter(getActivity(), mDatasSkeleton);
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_PAST_IMAGE.ordinal(), null));
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_NEW_GAME.ordinal(), null));
        mDatasSkeleton.add(new ViewBean(RecommendAdapter.ViewType.TYPE_BEST_MONTH.ordinal(), null));

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(adapter)
                .adapter(skeletonAdapter)
                .shimmer(true)
                .color(R.color.shimmer_color)
                .angle(20)
                .duration(1200).show();
    }

    void hideSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.hide();
    }

    void showSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.show();
    }

    private void initView() {
        LogUtils.e(TAG + " initView()");

        headerLl.setOnClickListener(this);
        adapter = new RecommendAdapter(getActivity(), viewBeans, this);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
//        recyclerView.addOnScrollListener(new MyScrollListener());
//        refreshLayout.setEnableHeaderTranslationContent(true);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
            }
        });

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean misAppbarExpand = true;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int scrollRange = appBarLayout.getTotalScrollRange();
                float fraction = 1f * (scrollRange + verticalOffset) / scrollRange;
                if (fraction>=1.0f) {
                    headerLl.setVisibility(View.GONE);
                } else {
                    headerLl.setVisibility(View.VISIBLE);
                }
                headerLl.setAlpha((1.0f - fraction)*2 + 0.4f);
            }
        });
    }

    private NetResultCacheTable table = null;
    private void initData() {
        try {
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("pn", pn+"");
            String requestStr = new Gson().toJson(tempMap);
            table = NetResultCacheManager.getInstance().getDataByUrl(RpcConstant.forumRootUrl+RpcConstant.indexData, requestStr);
            if (table != null && !StringUtils.isEmpty(table.getResponseStr())) {
                hideSkeleton();
                String data = table.getResponseStr();
                ResponseBase<IndexBeanResponse> temp = fromJsonObject(data, IndexBeanResponse.class);
                updataUi(temp.getData_info());
            } else {
                initSkeleton();
                showSkeleton();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        getIndexDataForFirst();
    }

    private void getIndexDataForFirst() {
        refreshLayout.setEnableLoadMore(true);
        pn = 1;
        poDotCo = 2;
        getIndexData();
    }

    public <T> ResponseBase<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new NetCallBack.ParameterizedTypeImpl(ResponseBase.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e(TAG + " onResume()");
        changeLoginStatus();
        changeTopStatus();
        StatFactory.getInstance().sendVistPage(getActivity(), "Index", "Index");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        changeLoginStatus();
        changeTopStatus();
        LogUtils.e(TAG + " onHiddenChanged():" + hidden);
    }

    private void changeTopStatus() {
        try {
            if (recommendTopDownloadTop != null) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (recommendTopDownloadTop != null) {
                            recommendTopDownloadTop.setTotalDownloadNum();
                        }
                    }
                }, 200);
            }
        } catch (Exception e) {
        }
    }

    private void changeLoginStatus() {
        try {
            AccountBean accountBean = AccountUtil.getInstance().getAccountData();
            if (AccountUtil.getInstance().getAccountData() == null) {//未登陆
                recommendTopNameTx.setText("0");
                recommendTopNumTx.setText("登录开始赚钱");
                tagNumTx.setVisibility(View.GONE);
                recommendTopEnergyTop.initNum(0);
            } else {//已登陆
                tagNumTx.setVisibility(View.VISIBLE);
                NumberFormat nf = new DecimalFormat(",###,##0.00");
                float wallet = accountBean.getWallet() / 100f;
                recommendTopNameTx.setText(nf.format(wallet));
                float lastWallet = accountBean.getLastWallet() / 100f;
                recommendTopNumTx.setText("+" + nf.format(lastWallet));
                recommendTopEnergyTop.initNum(accountBean.getEnergies());
            }

            String gameCount = MyApplication.cfgPlug.getValue_game_count();
            if (!StringUtils.isEmpty(gameCount))
                partSearchTx.setText(gameCount+"款游戏供你搜索");
        } catch (Exception e) {
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.layout_search_ll, R.id.recommendTopAdIv, R.id.tagHeadRl, R.id.notNetFl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tagHeadRl:
                if (AccountUtil.getInstance().getAccountData() == null)
                    IntentUtil.getInstance().goLoginActivity(getActivity());
                else
                    IntentUtil.getInstance().goShareWebActivity(getActivity(), MyApplication.cfgPlug.getValue_wallet_url_v2());
                break;
            case R.id.layout_search_ll:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.recommendTopAdIv://测试入口
                if (recommendTopAd != null && recommendTopAd.getJump_ad_switch()==1 ) {
                    IntentUtil.getInstance().intentTo(getActivity(), recommendTopAd);
                    StatFactory.getInstance().sendClickAdvertSpacePage(getActivity()
                            , AdPosition.getModeByEnum(0), AdPosition.getNameByEnum(0)
                            ,"","", 1);
                }
                break;
            case R.id.notNetFl:
                if (table==null)
                    showSkeleton();
                notNetFl.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                refreshLayout.autoRefresh();
                getIndexData();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_search_ll://搜索
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
            recommendTopDownloadTop.setTotalDownloadNum();

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            if (str.contains("|")) {
                String[] sl = str.split("\\|");
                GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(sl[0]), Integer.valueOf(sl[1]));
                if (bean == null) return;
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }
                View view = layoutManager.findViewByPosition(Integer.valueOf(sl[0]));
                if (view == null) {
                    return;
                }

                if (Integer.valueOf(sl[2])==0) {
                    ItemGridDownloadView itemView = null;
                    switch (Integer.valueOf(sl[1])) {
                        case 0:
                            itemView = view.findViewById(R.id.itemGridDownloadViewOne);
                            break;
                        case 1:
                            itemView = view.findViewById(R.id.itemGridDownloadViewTwo);
                            break;
                        case 2:
                            itemView = view.findViewById(R.id.itemGridDownloadViewThree);
                            break;
                    }

                    if (itemView == null) {
                        return;
                    }
                    DownloadViewStroke dowView = itemView.getDownView();
                    dowView.updateButn(table);
                } else if (Integer.valueOf(sl[2])==1) {
                    ItemGridDownloadBestView itemView1 = null;
                    switch (Integer.valueOf(sl[1])) {
                        case 0:
                            itemView1 = view.findViewById(R.id.itemGridDownloadViewOne);
                            break;
                        case 1:
                            itemView1 = view.findViewById(R.id.itemGridDownloadViewTwo);
                            break;
                        case 2:
                            itemView1 = view.findViewById(R.id.itemGridDownloadViewThree);
                            break;
                        case 3:
                            itemView1 = view.findViewById(R.id.itemGridDownloadViewFour);
                            break;
                        case 4:
                            itemView1 = view.findViewById(R.id.itemGridDownloadViewFive);
                            break;
                    }

                    if (itemView1 == null) {
                        return;
                    }
                    ItemBestMonthDownButn dowView = itemView1.getDownView();
                    dowView.updateButn(table);
                }
            } else {
                GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
                if (bean == null) return;
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }

                View view = layoutManager.findViewByPosition(Integer.valueOf(str));
                ItemListView itemView = view.findViewById(R.id.listItem);
                if (itemView == null) {
                    ItemListPartView itemView1 = view.findViewById(R.id.itemListPartView);
                    if (itemView1 == null) {
                        return;
                    }
                    DownloadViewStroke dowView = itemView1.getDownView();
                    dowView.updateButn(table);
                    return;
                }
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopEnergyTop != null) {
            recommendTopEnergyTop.addEnergyNum(energyEvent.getNumber());
            if (isVisible())
                ((BaseAppCompatActivity)getActivity()).showEnergyDialog(energyEvent.getNumber());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AccountChangeEvent accountChangeEvent) {
        changeLoginStatus();
        changeTopStatus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SensorChangedEvent sensorChangedEvent) {
        if (recommendTopEnergyTop != null) {
            recommendTopEnergyTop.changeRotate(sensorChangedEvent.degree);
        }
    }

    private void getIndexData() {
        api.getIndexData(pn).enqueue(new MyCallback<ResponseBase<IndexBeanResponse>>() {
            @Override
            public void onSuccess(ResponseBase<IndexBeanResponse> model) {
                if (pn==1) {
                    Gson gson = new Gson();
                    Map<String, String> tempMap = new HashMap<>();
                    tempMap.put("pn", pn+"");
                    String requestStr = gson.toJson(tempMap);
                    String retStr = gson.toJson(model);
                    String retUrl = RpcConstant.forumRootUrl+RpcConstant.indexData;
                    LogUtils.e("retUrl:"+retUrl+"\nrequestStr:"+requestStr+"\nretStr:"+retStr);
                    NetResultCacheManager.getInstance().insertData(retUrl, requestStr, retStr);
                }

                IndexBeanResponse data = model.getData_info();
                hideSkeleton();
                updataUi(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                try {
                    refreshLayout.finishLoadMore();
                    if (viewBeans.size()==0) {
                        if (code==-3){
                            notNetFl.setVisibility(View.VISIBLE);
                            refreshLayout.setVisibility(View.GONE);
                        }
                        if (pn==1) {
                            refreshLayout.finishRefresh();
                        } else {
                            hideSkeleton();
                            refreshLayout.setEnableLoadMore(false);
                        }
                    } else {
                        if (pn==1) {
                            refreshLayout.finishRefresh();
                        } else {
                            hideSkeleton();
                            refreshLayout.finishLoadMoreWithNoMoreData();
                        }
                    }
                } catch (Exception e) {
                    if (viewBeans.size()==0) {
                        if (code==-3){
                            notNetFl.setVisibility(View.VISIBLE);
                        }
                        if (pn==1) {
                        } else {
                            hideSkeleton();
                        }
                    } else {
                        if (pn==1) {
                        } else {
                            hideSkeleton();
                        }
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    private void updataUi(IndexBeanResponse data) {
        changeLoginStatus();

        if (data == null) {
           return;
        } else {
            if (notNetFl!=null)
                notNetFl.setVisibility(View.GONE);
            if (refreshLayout!=null)
                refreshLayout.setVisibility(View.VISIBLE);
        }
        if (pn==1) {
            viewBeans.clear();
            adapter.clearTempData();
        }

        //顶部广告位
        if (data.getRecommend_top_ad()!=null) {
            recommendTopAd = data.getRecommend_top_ad();
            if (recommendTopAd != null && recommendTopAd.getJump_ad_switch()==1
                    && !StringUtils.isEmpty(recommendTopAd.getJump_cover_big_pic())) {
                if (recommendTopAdIv != null)
                    recommendTopAdIv.setImageURI(recommendTopAd.getJump_cover_big_pic());
            }
        }

        //banner图片
        JumpBaseBean bannerBean = data.getRecommend_banner();
        if (bannerBean != null) {
            bannerBean.setDotMode(AdPosition.getModeByEnum(5));
            bannerBean.setDotName(AdPosition.getNameByEnum(5));
            bannerBean.setPosition(1);
            RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_IMAGE, bannerBean);
            viewBeans.add(viewBean);
        }

        //每日上新和每日首发
        List<JumpBaseBean> listTemp = new ArrayList<>();
        JumpBaseBean edn = data.getRecommend_edn();
        if (edn != null) {//每日上新
            edn.setDotMode(AdPosition.getModeByEnum(1));
            edn.setDotName(AdPosition.getNameByEnum(1));
            edn.setPosition(1);
            listTemp.add(edn);
        }
        JumpBaseBean tf = data.getRecommend_tf();
        if (tf != null) {//每日首发
            tf.setDotMode(AdPosition.getModeByEnum(2));
            tf.setDotName(AdPosition.getNameByEnum(2));
            tf.setPosition(1);
            listTemp.add(tf);
        }
        if (listTemp.size() > 0) {
            RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_NEW_GAME, listTemp);
            viewBeans.add(viewBean);
        }

        //月最佳
        JumpBaseBean bestMonth = data.getRecommend_best_month();
        if (bestMonth != null) {
            RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_BEST_MONTH, bestMonth);
            viewBeans.add(viewBean);
        }

        //合并专题列表
        List<JumpBaseBean> spCollectionMonth = data.getRecommend_sp_collection();
        if (spCollectionMonth!=null) {
            List<JumpBaseBean> spTempList = new ArrayList<>();
            for (int i=0;i<spCollectionMonth.size();i++) {
                JumpBaseBean temp = spCollectionMonth.get(i);
                temp.setDotMode(AdPosition.getModeByEnum(4));
                temp.setDotName(AdPosition.getNameByEnum(4));
                temp.setPosition(i+1);
                spTempList.add(temp);
                if (i==(spCollectionMonth.size()-1) || spTempList.size()==2) {
                    List<JumpBaseBean> add = new ArrayList<>();
                    add.addAll(spTempList);
                    RecommendAdapter.ViewBean view = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_SP_COLLECTION, add);
                    viewBeans.add(view);
                    spTempList.clear();
                    if (i!=(spCollectionMonth.size()-1)) {
                        RecommendAdapter.ViewBean viewLine = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_LINE_1PX, add);
                        viewBeans.add(viewLine);
                    }
                }
            }
        }

        //月最佳
        JumpBaseBean pastCollection = data.getRecommend_best_collection();
        if (pastCollection != null) {
            pastCollection.setDotMode(AdPosition.getModeByEnum(4));
            pastCollection.setDotName(AdPosition.getNameByEnum(4));
            pastCollection.setPosition(5);
            RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_COLLECTION, pastCollection);
            viewBeans.add(viewBean);
        }

        //往期经典
        List<JumpBaseBean> pastData = data.getRecommend_past_period();
        if (pastData != null && pastData.size()>0) {
            if (poDotCo<=2) {
                RecommendAdapter.ViewBean viewTitle = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_TITLE, pastData);
                viewBeans.add(viewTitle);
            }
            for (int i=0;i<pastData.size();i++) {
                JumpBaseBean past = pastData.get(i);
                if (poDotCo<=6) {
                    past.setDotMode(AdPosition.getModeByEnum(5));
                    past.setDotName(AdPosition.getNameByEnum(5));
                    past.setPosition(poDotCo);
                    poDotCo += 1;
                }
                RecommendAdapter.ViewBean viewImg = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_IMAGE, past);
                viewBeans.add(viewImg);
                if (past.getGame_list()!=null && past.getGame_list().size()>0){
                    RecommendAdapter.ViewBean viewList = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_LIST, past);
                    viewBeans.add(viewList);
                }
                RecommendAdapter.ViewBean lineBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_PAST_LIST_LINE, null);
                viewBeans.add(lineBean);
            }
        }

        //精选
        if (data.getRecommend_game_list_v1() != null) {
            for (int i = 0; i < data.getRecommend_game_list_v1().size(); i++) {
                JumpBaseBean temp = data.getRecommend_game_list_v1().get(i);
                if (temp.getGame_list() != null && temp.getGame_list().size() > 0) {
                    RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_TITLE, temp);
                    viewBeans.add(viewBean);

                    int total = temp.getGame_list().size();
                    List<GameListBaseBean> gridTemp = new ArrayList<>();
                    for (int n = 0; n < total; n++) {
                        gridTemp.add(temp.getGame_list().get(n));
                        if (gridTemp.size() == 3 || n == (total - 1)) {
                            List<GameListBaseBean> add = new ArrayList<>();
                            add.addAll(gridTemp);
                            RecommendAdapter.ViewBean view = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_GRID, add);
                            viewBeans.add(view);
                            gridTemp.clear();
                        }
                    }
                }
            }
        }

        //热门
        if (data.getRecommend_game_list_v2() != null) {
            for (int i = 0; i < data.getRecommend_game_list_v2().size(); i++) {
                JumpBaseBean temp = data.getRecommend_game_list_v2().get(i);
                if (temp.getGame_list() != null && temp.getGame_list().size() > 0) {
                    RecommendAdapter.ViewBean viewBean = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_TITLE, temp);
                    viewBeans.add(viewBean);

                    int total = temp.getGame_list().size();
                    for (int n = 0; n < total; n++) {
                        RecommendAdapter.ViewBean view = new RecommendAdapter.ViewBean(RecommendAdapter.ViewType.TYPE_LIST, temp.getGame_list().get(n));
                        viewBeans.add(view);
                    }
                }
            }
        }

        adapter.notifyDataSetChanged();
if (refreshLayout!=null)
        if (data == null
                || data.getRecommend_past_period()==null
                || data.getRecommend_past_period().size()==0) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            if (pn==1)
                refreshLayout.finishRefresh();
            else
                refreshLayout.finishLoadMore();
            pn += 1;
        }
    }

    @Override
    public void onResult(long time) {
        if (time <= 0) {
            refreshLayout.autoRefresh();
        }
    }
}
